
import os
import uuid
from datetime import timedelta

from flask import Blueprint, jsonify, request, send_from_directory
from flask_cors import CORS
from src.main.dao.ModuleDao import ModuleDao
from src.main.dao.UserDao import UserDao
from src.main.domain.DataConverter import DataConverter
from src.main.domain.UserConverter import UserConverter
from src.main.domain.system.Module import Module
from src.main.domain.system.User import User
from src.main.util import Utils
from src.main.util.MinioClient import minio_client
from src.main.util.ApplicationConfig import ApplicationConfig

system_blueprint = Blueprint('system', __name__)
CORS(system_blueprint)

# 用户注册接口
@system_blueprint.route('/userRegister', methods=['POST'])
def user_register():
    user_dao = UserDao()
    user_dao.connect()
    username = request.json.get('username')
    password = request.json.get('password')
    existing_user = user_dao.get_user_by_username(username)
    if existing_user:
        response = {'success': False, 'msg': '用户名已存在'}
    else:
        user_dao.insert(username, password)
        response = {'success': True, 'msg': '注册成功'}
    return jsonify(response)

# 用户登录接口
@system_blueprint.route('/userLogin', methods=['POST'])
def user_login():
    username = request.json.get('username')
    password = request.json.get('password')
    user_dao = UserDao()
    user_dao.connect()
    user_info = user_dao.get_user_by_username(username)
    if user_info and len(user_info) > 0:
        stored_password = user_info[0][2]
        if password == stored_password:
            response = {'success': True, 'msg': '登录成功'}
        else:
            response = {'success': False, 'msg': '密码错误'}
    else:
        response = {'success': False, 'msg': '用户不存在'}
    return jsonify(response)

# 查询所有模块数据
@system_blueprint.route('/getModules', methods=['GET'])
def get_modules():
    dao = ModuleDao()
    dao.connect()
    results = dao.get_all_modules()
    modules = DataConverter.convert_results_to_objects(results, Module)
    data = DataConverter.convert_objects_to_json(modules)
    # 构建树形结构
    tree = Utils.build_tree(data)
    print(tree)
    response = {'success': True, 'data': tree}
    return jsonify(response)

# 查询用户信息
@system_blueprint.route('/getUsers', methods=['POST'])
def get_users():
    dao = UserDao()
    dao.connect()
    pageNumber = request.json.get('pageNumber')
    pageSize = request.json.get('pageSize')
    filter_keyword = request.json.get('filterKeyword')
    results = dao.get_user_info_by_page(pageNumber, pageSize,filter_keyword)
    users = UserConverter.convert_results_to_objects(results, User)
    data = UserConverter.convert_objects_to_json(users)
    print(1111111)
    print(data)

    response = {'success': True, 'data': data}
    return jsonify(response)

# 新增或更新学生信息
@system_blueprint.route('/saveOrUpdateUser', methods=['POST'])
def save_or_update_user():
    dao = UserDao()
    dao.connect()
    # 处理文件上传
    if 'avatarFile' in request.files:
        file = request.files['avatarFile']
        if file.filename != '':  # 确保文件存在
            app_config = ApplicationConfig()
            root_dir = app_config.get_root_dir()
            upload_dir = app_config.get_upload_config()
            upload_path = os.path.join(root_dir, upload_dir)
            # 检查目录是否存在，如果不存在则创建
            if not os.path.exists(upload_path):
                print("上传路径:", upload_path)
                os.makedirs(upload_path)

            file_name = f"{uuid.uuid4().hex}.{file.filename}"
            file_path = os.path.join(upload_path, file_name)
            # 先上传到本地
            file.save(file_path)

            object_name = f'ibai-tools/user-avatars/{file_name}'
            minio_config = app_config.get_minio()
            bucket_name = minio_config.get('bucket_name')
            endpoint = minio_config.get('endpoint')
            access_key = minio_config.get('access_key')
            secret_key = minio_config.get('secret_key')

            # 检查桶是否存在，如果不存在则创建
            client = minio_client(endpoint, access_key, secret_key)
            client.create_bucket(bucket_name)
            print(file)
            # 上传文件到 MinIO
            client.put_object_by_path(bucket_name,file_path,object_name)
            # 获取文件的公共访问URL
            # avatar_url = client.get_presigned_url(bucket_name, object_name, expires=timedelta(hours=1))  # URL有效期为1小时
            # print(f"Avatar URL: {avatar_url}")
            # except Exception as e:
            #     return jsonify({'success': False, 'error': str(e)}), 500

    # 从请求中获取表单数据（不包括文件）
    user_data = request.form.to_dict()
    user_data['avatarPath'] = object_name
    user = User(**user_data)


    # 调用保存或更新逻辑
    row_count = dao.saveOrUpdate(user)  # 假设saveOrUpdate现在接收一个字典
    success = row_count > 0
    response = {'success': success}
    return jsonify(response)


@system_blueprint.route('/get_user_image/<int:user_id>')
def get_user_image(user_id):
    dao = UserDao()
    dao.connect()
    user = dao.get_user_by_id(user_id)
    user_info = User(*user[0])

    # 获取图片文件名（或完整路径）
    filename = user_info.get_avatar_path()
    if not filename:
        # 如果找不到图片，返回404错误
        return jsonify({'error': 'Image not found for user_id: ' + str(user_id)}), 404

    base_path = os.path.dirname(filename)
    file_name = os.path.basename(filename)

    # 发送图片作为响应
    # 注意：你需要设置正确的MIME类型，这里假设是JPEG图片
    if os.path.isfile(filename):
        return send_from_directory(base_path,file_name,mimetype='image/jpeg')
    else:
        # 如果文件不存在，返回404错误
        return jsonify({'error': 'File does not exist: ' + filename}), 404

# 删除学生信息
@system_blueprint.route('/deleteUser', methods=['GET'])  # 改为 GET 方法
def delete_user():
    dao = UserDao()
    dao.connect()
    id = request.args.get('id', 0)
    if id:
        id = int(id)  # 将 id 转换为整数
        row_count = dao.delete(id)
    success = row_count > 0  # 根据受影响的行数判断操作是否成功

    response = {'success': success}
    return jsonify(response)